package com.manager.util;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class JSONUtil {
	/*
	 * 常用的JSON简单的转换函数
	 * (1)List To JSON
	 * (2)Map To JSON
	 * (3)List<Map> to JSON
	 */
	
	/*
	 * List<Map> to JSON
	 */
	public static StringBuffer listMapToJSON(List list){
		StringBuffer sb = null;
		
		if(list != null && list.size() > 0){
			sb = new StringBuffer();
			sb.append("[");
			
			//取默认的标题
			Map m1 = (Map)list.get(0);
			Iterator it1 = m1.entrySet().iterator();
			sb.append("{");
			while(it1.hasNext()){
				Entry entry = (Entry)it1.next();
				sb.append("\"").append(entry.getKey().toString()).append("\"");
				sb.append(":");
				sb.append("\"").append(entry.getKey().toString()).append("\"");
				sb.append(",");
			}
			sb.deleteCharAt(sb.length() - 1);//删除多余的","
			sb.append("},");
			
			//添加正文内容
			for(int i = 0; i< list.size(); i++){
				Map m = (Map)list.get(i);
				Iterator it = m.entrySet().iterator();
				
				sb.append("{");
				while(it.hasNext()){
					Entry entry = (Entry)it.next();
					sb.append("\"").append(entry.getKey().toString()).append("\"");
					sb.append(":");
					sb.append("\"").append(entry.getValue().toString()).append("\"");
					sb.append(",");
				}
				sb.deleteCharAt(sb.length() - 1);//删除多余的","
				sb.append("},");
			}
			sb.deleteCharAt(sb.length() - 1);//删除多余的","
			
			sb.append("]");
		}
		
		return sb;
	}
	
	public static void main(String[] args) {
		
	}

}
